import axios from 'axios'
import store from '@/store'
import { customHistory } from './history'
import { Toast } from 'antd-mobile'
import { removeToken, setToken } from './token'
const baseURL = 'http://toutiao.itheima.net/v1_0'

const http = axios.create({
  baseURL,
  timeout: 5000,
})
// 请求拦截器
http.interceptors.request.use((config) => {
  // 获取token
  const {
    login: { token },
  } = store.getState()
  // 除了登录请求外，其他请求统一添加 token
  if (!config.url?.startsWith('/authorizations')) {
    config.headers!.Authorization = `Bearer ${token}`
  }
  return config
})
// 响应拦截器
http.interceptors.response.use(undefined, async (error) => {
  if (!error.response) {
    Toast.show({
      content: '网络繁忙，请稍后重试',
      duration: 1000,
    })
    return Promise.reject(error)
  }

  if (error.response.status === 401) {
    try {
      const { refresh_token } = store.getState().login
      if (!refresh_token) {
        // 1 手动抛出异常
        throw new Error(error)
      } else {
        //无感刷新token
        const res = await axios.put(`${baseURL}/authorizations`, null, {
          headers: {
            Authorization: `Bearer ${refresh_token}`,
          },
        })
        const tokens = { token: res.data.data.token, refresh_token }
        setToken(tokens)
        store.dispatch({ type: 'login/token', payload: tokens })

        return http(error.config)
      }
    } catch (e) {
      //清除redux的token
      store.dispatch({ type: 'login/logout' })
      // 手动清理本地的 token
      removeToken()
      Toast.show({
        content: '登录超时，请重新登录',
        duration: 1000,
        afterClose: () => {
          customHistory.push('/login', {
            from: customHistory.location.pathname,
          })
        },
      })
      return Promise.reject(error)
    }
  }
})
export default http
